package com.zyl.blog.common.handler;

import com.zyl.blog.common.enums.OpenStatus;
import com.zyl.blog.common.exception.BlogException;
import com.zyl.blog.common.utils.Extreme.LogUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @version v1.0
 * @ProjectName: Personal_Blog
 * @Package: com.zyl.common.handler
 * @ClassName: OpenStatusHandler
 * @Description
 * @Author FinalFantasy
 * @Date 2025/2/17-20:28
 */
public class OpenStatusHandler extends BaseTypeHandler<OpenStatus> {

    /**
     * 设置非空参数
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    OpenStatus parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
    }

    /**
     * 处理结果集转换（根据列名）
     */
    @Override
    public OpenStatus getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseCode(rs.getInt(columnName));
    }

    /**
     * 处理结果集转换（根据列索引）
     */
    @Override
    public OpenStatus getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseCode(rs.getInt(columnIndex));
    }

    /**
     * 处理CallableStatement结果
     */
    @Override
    public OpenStatus getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseCode(cs.getInt(columnIndex));
    }

    /**
     * 统一解析逻辑
     */
    private OpenStatus parseCode(int code) {
        try {
            return OpenStatus.fromCode(code);
        } catch (IllegalArgumentException e) {
            LogUtil.error("数据库开放状态值解析异常，异常编码：{}", e, code);
            throw new BlogException("系统状态数据异常", e);
        }
    }
}